<template>
  <div class="articleDetail">

    <el-steps :active="active" finish-status="success" class="steps">
      <el-step title="步骤 1">1</el-step>
      <el-step title="步骤 2">2</el-step>
      <el-step title="步骤 3">3</el-step>
    </el-steps>


    <!--    步骤1 填写相关信息-->
    <div class="step step3 info" v-if="active == 1">

      <el-form ref="form" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="article.title"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="article.author" disabled/>
        </el-form-item>
        <el-form-item label="原作">
          <el-input v-model="article.originalAuthor"/>
        </el-form-item>
        <el-form-item label="分类">
          <!--          <el-select v-model="article.categoryName" placeholder="请选择分类"  filterable default-first-option>-->
          <!--            &lt;!&ndash;            <el-option label="加载中..." :value="''" disabled v-if="article.categoryName == null"></el-option>&ndash;&gt;-->
          <!--            <el-option v-for="(item,index) in categoryList" :key="index" :label="item.categoryName"-->
          <!--                       :value="item.categoryName"></el-option>-->
          <!--          </el-select>-->

          <el-cascader
            v-if="categoryList.length!=0  "
            v-model="categoryArray"
            :options="categoryList"
            :props="cascaderProps"
            :show-all-levels="false"
            expandTrigger="hover"
            @change="categoryGetLastItem"
            clearable></el-cascader>


          <!--            <el-option label="加载中..." :value="''" disabled v-if="article.categoryName == null"></el-option>-->

        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="article.tagsList" placeholder="请选择标签" default-first-option allow-create multiple>
            <!--            <el-option label="加载中..." :value="''" disabled v-if="article.tagsName == null"></el-option>-->
            <el-option v-for="(item,index) in tagsList" :key="item.id" :label="item.tagsName" v-if="tagsList.length!=0"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="私密/公有文章">
          <el-switch v-model="article.status"
                     active-color="#13ce66" inactive-color="#ff4949"
                     :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="article.summary" type="textarea"/>
        </el-form-item>
      </el-form>

    </div>

    <!--    步骤2  编写文章-->
    <div class="step step2 articleContent" v-if="active == 2">


      <div class="markdown">
        <MarkdownPro
          :autoSave="true"
          v-model='markdownContent'
          :initialValue='article.content'
        />
      </div>
    </div>

    <!--    步骤2 上传首页图片-->
    <div class="step step3 upload" v-if="active == 3" style="text-align: center">
      <div class="upload-info">

        <div v-if="article.imgUrl == null"><h2> 请上传文章首页图</h2></div>
        <div>

          <div v-if="article.imgUrl != null"><h2> 文章首页图</h2></div>

          <el-upload
            class="avatar-uploader"
            :action="domain"
            :data="QiniuData"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="article.imgUrl != null" :src="article.imgUrl" class="avatar"
                 style="margin: auto;background-position:center;background-size:contain">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>


          <div class="imgUrlClass">
            <span>图片地址: &nbsp;</span>
            <el-input v-model="article.imgUrl" placeholder="图片地址" style="width:50% "/>
          </div>




        </div>
        <div>
        </div>
      </div>
    </div>


    <div class="btn-group">
      <el-button type="primary" size="small" icon="el-icon-arrow-left
" @click="pre" :disabled="active == 1?true:false">上一步</el-button>
      <el-button type="danger" size="small" icon="el-icon-arrow-right
" @click="next" :disabled="active == 3?true:false">下一步</el-button>
      <el-button type="success"  size="small" icon="el-icon-check" @click="saveArticle()" v-if="(active == 3?true:false) && (parentArticle == null) && $store.getters.button.includes('article:add')">添 加
      </el-button>
      <el-button type="success" size="small" icon="el-icon-check" @click="updateArticle()" v-if="parentArticle != null && $store.getters.button.includes('article:update')">更 新</el-button>
    </div>
  </div>

</template>

<script>
  import { getCategoryList } from '@/api/category'
  import { getTagsList } from '@/api/tags'
  import { getArticleContent,updateArticle } from '@/api/article'
  import { getQiNiuToken } from '@/api/qiniu'
  import MarkdownPro from 'vue-meditor'
  import { saveArticle } from '../../api/article'
  import { mapGetters } from 'vuex'

  export default {
    name: 'index',
    props: {
      'parentArticle': {
        type: Object,
        default: null
      },
      'categoryListTree':[Object,Array],
      'parentTagsList':[Object,Array],
    },
    data() {
      return {
        active: 1,
        //标签列表
        tagsList: [Object,Array],
        //分类列表
        categoryList: [Object,Array],
        //级联属性
        cascaderProps: {
          checkStrictly: true,
          label: 'categoryName',
          value: 'id',
          children: 'children',
        },
        markdownContent: '',
        categoryArray:[],

        article: {
          // articleId: '',
          userId: 1236558231564722178,
          title: '',
          summary: '',
          author: this.name,
          imgUrl: 'http://res.cofa.top/upload_pic_%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200310155532.jpg',
          content: '',
          categoryId: null,
          tagsList:[],
          originalAuthor: this.name,
          status: 1,
          content: ''
        },
        imageUrl: '',

        // 七牛云提交数据
        QiniuData: {
          key: '', //图片名字处理
          token: '' //七牛云token
        },
        // 提交地址
        domain: 'https://upload-z2.qiniup.com', // 七牛云的上传地址（华南区）
        // 图片外链地址
        qiniuaddr: 'http://res.cofa.top/' // 七牛云的图片外链地址

      }
    },
    computed: {
      ...mapGetters([
        'name',
      ])
    },
    created() {

      /**
       * 获取七牛云Token
       * */
      this.getQiNiuToken()

    },
    mounted: function() {

      this.article.author = this.name
      this.article.originalAuthor = this.name

      /**
       * 获取标签列表
       */
      this.getTagsList()
      /**
       * 获取分类列表
       */
      this.getCategoryList()

      // 父组件传递数据过来时 更新数据
      if (this.parentArticle != null) {

        this.article = this.parentArticle
        this.categoryList = this.categoryListTree
        this.tagsList = this.parentTagsList

        this.parseTags(this.article.tags)
        this.parseCategory(this.article.category.id)

        this.getArticleContent(this.article.id)


      }

      // console.log("父组件articleId：" + this.articleId)
    },
    methods: {

      /**
       * 下一步
       */
      next() {
        if (this.active != 3) {
          this.active++
        }
      },
      /**
       * 上一步
       */
      pre() {
        if (this.active != 0) {
          this.active--
        }
      },

      /**
       * 获取标签列表
       */
      getTagsList() {

        // api获取
        if (this.parentTagsList!=undefined) return
        getTagsList().then(response => {

          if (response.code == 200) {
            const { data } = response
            // 更新数据
            this.tagsList = data
          }

        }).catch(error => {
          console.log(error)
        })

      },

      /**
       * 获取分类列表
       */
      getCategoryList() {

        if (this.categoryListTree!=undefined) return
        // api获取
        getCategoryList().then(response => {

          if (response.code == 200) {
            const { data } = response
            // 更新数据
            this.categoryList = this.getTreeData(data)
          }

        }).catch(error => {
          console.log(error)
        })
      },

      // 递归判断列表，把最后的children设为undefined
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children === null || data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children)
          }
        }
        return data
      },

      /**
       * 提交文章
       */
      saveArticle() {
        this.article.content = this.markdownContent

        console.log(JSON.stringify(this.article))
        // api获取
        saveArticle(this.article).then(response => {

          if (response.code == 200) {

            this.$message({
              showClose: true,
              message: response.message,
              type: 'success',
              center: true
            })

            this.$router.push({ name: 'ArticleList' })

          }


        }).catch(error => {
          console.log(error);
        })

      },

      /**
       * 更新文章
       * */
      updateArticle() {
        this.article.content = this.markdownContent
        this.categoryGetLastItem()

        console.log(JSON.stringify(this.article))

        const articleInfo = JSON.parse(JSON.stringify(this.article))
        delete articleInfo.category
        delete articleInfo.tags

        // api获取
        updateArticle(this.article.id,articleInfo).then(response => {

          if (response.code == 200) {

            this.$message({
              showClose: true,
              message: response.message,
              type: 'success',
              center: true
            })

            // 向父组件发送更新内容
            var obj = JSON.parse(JSON.stringify(this.article))
            this.$emit('updateArticle', obj)

          }


        }).catch(error => {
          console.log(error);
        })

      },

      /**
       *
       * 通过文章ID 获取文章内容
       * */
      getArticleContent(id) {

        // api获取
        getArticleContent(id).then(response => {

          if (response.code == 200) {
            const { data } = response

            console.log('getArticleContent:' + JSON.stringify(data))

            this.article.content =  data;
            this.markdownContent = data
          }
          return '# 该文章暂无内容';


        }).catch(error => {
          console.log(error);
        })
      },

      /**
       * 转换标签
       * */
      parseTags(tags) {
        if (this.article.tagsList == null){
          this.article.tagsList = []
        }
        tags.forEach(item=>{
          if (item.id != null) {
            if(this.article.tagsList.indexOf(item.id) == -1){
              this.article.tagsList.push(item.id)
            }
          }
        })
      },


      /**
       * 转换分类
       * */
      parseCategory(id,categoryList = this.categoryList, path = []){
        /**
         * 遍历该层每一行数据
         */



        if (categoryList!= null) {
          for (var i = 0; i < categoryList.length; i++) {

            // 将 分类名 添加进 path
            path.push(categoryList[i].id)

            // 如果当前该分类id与分类名相同 则用nowCategoryPath接收结果
            if (categoryList[i].id == id) {
              console.log('结果:' + path.toString())
              this.categoryArray = path
              return path
            }

            // 如果该分类不符合 则找 子分类
            if (categoryList[i].children != null && categoryList[i].children.length != 0) {

              var result = this.parseCategory(id, categoryList[i].children, path)
              if (result != undefined) {
                return result
              }
            }

            // 如果上部分全不符合
            // 将 分类名 移出 path
            path.pop()
            // 找第一层小一条记录

          }
        }
      },

      /**
       *
       * 获取上传Token  七牛云
       * */
      getQiNiuToken() {

        // api获取
        getQiNiuToken().then(response => {

          if (response.code == 200) {
            const { data } = response
            this.QiniuData.token = data
          }
        }).catch(error => {
          console.log(error)
        })
      },

      /***
       *
       * 上传图片前
       * */
      beforeAvatarUpload(file) {
        const isPNG = file.type === 'image/png'
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isPNG && !isJPEG && !isJPG) {
          this.$message.error('上传头像图片只能是 jpg、png、jpeg 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return false
        }
        this.QiniuData.key = `upload_pic_${file.name}`

        /**
         * 获取上传token
         */
        this.getQiNiuToken()
      },

      /**
       * 图片上传成功
       * */
      uploadSuccess(response, file, fileList) {
        // console.log(fileList)
        this.article.imgUrl = `${this.qiniuaddr}/${response.key}`
        // console.log(this.article.imgUrl)
      },

      /**
       * 图片上传出错
       * @param err
       * @param file
       * @param fileList
       */
      uploadError(err, file, fileList) {
        this.$message({
          message: '上传出错，请重试！',
          type: 'error',
          center: true
        })
      },

      /**
       * 获取categoryArray最后一个元素 给 article的categoryId
       */
      categoryGetLastItem() {
        if (this.categoryArray.length!=0) {
          this.article.categoryId = this.categoryArray[this.categoryArray.length - 1]
        }
      }

    },
    watch: {
      //深度监听父组件parentArticle变化,当父组件点击其他按钮时,更新视图
      parentArticle: {
        handler(newV, oldV) {

          this.article = newV
          this.parseTags(this.article.tags)
          this.parseCategory(this.article.category.id)
          this.getArticleContent(this.article.id)

          this.active = 1
        },
        deep: false
      },
      categoryListTree:{
        handler(newV,oldV){
          this.categoryList = newV
        },
        deep:false
      },
      parentTagsList:{
        handler(newV,oldV){
          this.tagsList = newV
        },
        deep:false
      },



    },

    components: {
      MarkdownPro
    }
  }
</script>

<style>

  .steps {
    margin-top: 10px;
    margin-bottom: 20px;
    margin-left: auto;
    margin-right: auto;
    width: 90%;
  }

  .articleDetail {
    margin: 20px;
    width: 90%;
  }

  .step {
    margin-top: 20px
  }

  .step2 {
    margin-left: 40px;
    margin-right: 40px;
    margin-top: 20px;
  }

  .btn-group {
    margin-top: 30px;
    text-align: center;
  }


  .articleDetail .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
    height: 200px;
  }

  .articleDetail .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .articleDetail .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .articleDetail .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .imgUrlClass{
    margin: 10px auto;
  }


</style>
